﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTOFrameworks;
using System.Data;
using PhysicalDataProvider;
using FooFun.DataElements.Dtos;
using System.Collections;
using AccessGrant.GrantFrameworks;
using System.Data.Common;

namespace FAQFrameworks
{
    public class UserManager
    {
        UserService userService;

        public UserManager()
        {
            userService = new UserService();
        }

        public bool ValidateUser
            (string loginName, string password, out LoginUser user)
        {
            string sql;
            if (loginName.IndexOf("@") < 0)
            {
                sql = @"SELECT * 
FROM t_Users,t_Accounts 
WHERE t_Accounts.AccountId = t_Users.UserId 
AND AccountName = '" + loginName + "'";
            }
            else
            {
                sql = @"SELECT * FROM t_Users,t_Accounts 
WHERE t_Accounts.AccountId = t_Users.UserId 
AND LoginName = '" + loginName + "'";
            }

            DataTable table = DataService.FillTable(sql);

            if (table.Rows.Count == 0)
            {
                user = null;
                return false;
            }

            DataRow row = table.Rows[0];

            string dbPassword = (string)row["Password"];
            string dbGuidStr = (string)row["EncryptCode"];

            Guid guid = new Guid(dbGuidStr);

            Guid encodeGuid
                = AuthenticationUtil.MakeMD5Hash(guid, password);

            if (encodeGuid.ToString() == dbPassword)
            {
                user = new LoginUser();
                user.AccountId = DataProviderUtil.GetGuid(
                    row["UserId"]);

                return true;
            }
            else
            {
                user = null;
                return false;
            }
        }

        //        public FAQUser GetUserById(int id)
        //        {
        //            DataTable table = DataService.FillTable(
        //                @"SELECT * FROM t_Users,t_Accounts WHERE 
        //t_Accounts.AccountId = t_Users.UserId AND UserId =" + id);

        //            DataRow row = table.Rows[0];

        //            FAQUser user = new FAQUser();
        //            user.LoginName = (string)row["LoginName"];

        //            Account account = new Account();
        //            account.AccountName = (string)row["AccountName"];
        //            account.AccountId = DataProviderUtil.ParseGuid(row["AccountId"].ToString());

        //            user.Account = account;

        //            return user;
        //        }

        public IDataElement GetElement(object obj)
        {
            return userService.GetElement(obj);
        }

        public IDataElement GetElement(IDataElement obj)
        {
            return userService.GetElement(obj);
        }

        public void ChangePassword(Guid userId, string pwd)
        {
            userService.ChangePassword(userId, pwd);
        }

        public IDataElement ListManagerInForum(Guid forumId)
        {
            PermissionQuery query = PermissionQuery.Create();

            IEnumItem role = query.GetAccountByName("版主");
            IEnumItem forum = query.GetObjectById(forumId);

            RoleSetQuery roleSet = RoleSetQuery.Create();
            IDataElement de
                = roleSet.ListUserOfRoleInForum(role, forum);

            //return new UserIndexDataElement(de);
            return de;
        }

        class UserIndexDataElement : CustomDataElement
        {
            public UserIndexDataElement(IDataElement de)
                : base(de)
            {
                manager = new UserManager();
            }

            UserManager manager;

            public override IEnumerator GetEnumerator()
            {
                foreach (IDataElement item in this.InnerDataElement)
                {
                    IDataElement user
                        = manager.GetElement(item["UserId"]);
                    yield return user;
                }
            }
        }

        static Dictionary<Guid, DateTime> updateList
            = new Dictionary<Guid, DateTime>();

        public void UpdateLastVisiteTime(Guid guid)
        {
            lock (updateList)
            {
                using (DbConnection conn = SqlHelper.Connection)
                {
                    DbCommand cmd = conn.CreateCommand();
                    cmd.CommandText = @"DELETE FROM t_UserProfiles
WHERE UserId=?";
                    DbParameter para = cmd.CreateParameter();
                    para.Value = DataProviderUtil.GetGuidBase64(guid);

                    cmd.Parameters.Add(para);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                    cmd.CommandText = @"INSERT INTO t_UserProfiles
(UserId,LastVisitTime) VALUES (?,?)";

                    DbParameter para1 = cmd.CreateParameter();
                    para1.Value = DateTime.Now.ToString();

                    cmd.Parameters.Add(para1);

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }
        }

        public DateTime GetLastVisiteTime(Guid userId)
        {
            using (DbConnection conn = SqlHelper.Connection)
            {
                DbCommand cmd = conn.CreateCommand();
                cmd.CommandText = @"SELECT [LastVisitTime] 
FROM [t_UserProfiles] WHERE [UserId]=?";
                DbParameter para = cmd.CreateParameter();
                para.DbType = DbType.String;
                para.Value = DataProviderUtil.GetGuidBase64(userId);

                cmd.Parameters.Add(para);

                conn.Open();

                object obj = cmd.ExecuteScalar();

                // 默认一周
                DateTime time = DateTime.Now.AddDays(-7);
                if (obj != null && !(obj is DBNull))
                {
                    time = (DateTime)obj;
                }

                conn.Close();

                return time;
            }
        }
    }
}
